package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private EmpService empService;
    /**
     * 分页
     *
     * @param name
     * @param begin
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Clazz> findPage(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        //创建分页对象
        IPage<Clazz> iPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Clazz> wrapper = Wrappers.lambdaQuery();
        if(StringUtils.hasText(name)){
            wrapper.like(Clazz::getName,name);
        }
        if(begin != null && end != null){
            wrapper.between(Clazz::getUpdateTime,begin,end);
        }
        // 添加倒序排序
        wrapper.orderByDesc(Clazz::getUpdateTime);
        //执行分页查询
        iPage = this.page(iPage,wrapper);
        //获取查询结果
        List<Clazz> records = iPage.getRecords();
        long total = iPage.getTotal();
        // 关联封装Clazz表中的班主任姓名
        if(!CollectionUtils.isEmpty(records) && records.stream().anyMatch(clazz -> clazz.getMasterId() != null)){
            // 获取所有的班主任id
            List<Integer> masterIds = records.stream()
                    .map(Clazz::getMasterId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .toList();

            if(!masterIds.isEmpty()){
                // 根据员工id查询员工姓名
                List<Emp> emps = empService.listByIds(masterIds);
                // 为每个clazz对象的masterName赋值
                records.forEach(clazz -> {
                    if(clazz.getMasterId() != null){
                        emps.stream()
                                .filter(emp -> emp.getId().equals(clazz.getMasterId()))
                                .findFirst()
                                .ifPresent(emp -> clazz.setMasterName(emp.getName()));
                    }
                });
            }
        }

        // 为clazz表中的status赋值
        records.forEach(clazz -> {
            if(clazz.getBeginDate() != null && clazz.getEndDate() != null){
                if(clazz.getEndDate().isBefore(LocalDate.now())){
                    clazz.setStatus("已结课");
                } else if(clazz.getBeginDate().isAfter(LocalDate.now())){
                    clazz.setStatus("未开班");
                } else {
                    clazz.setStatus("在读");
                }
            }
        });
        // 封装结果
        return new PageResult<>(total, records);
    }
    //@Override 方法二
    public PageResult<Clazz> findAll(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        IPage<Clazz> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Clazz> queryWrapper = Wrappers.<Clazz>lambdaQuery()
                .like(name != null, Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getEndDate, begin, end);
        queryWrapper.orderByDesc(Clazz::getUpdateTime);
        // 调用分页
        IPage<Clazz> iPage = this.page(pageInfo, queryWrapper);
        List<Clazz> records = iPage.getRecords();
        long total = iPage.getTotal();

        // 关联封装Clazz表中的班主任姓名
        if(!CollectionUtils.isEmpty(records)){
            // 获取所有的员工id
            List<Integer> clazzIds = records.stream().map(clazz -> clazz.getMasterId()).toList();
            // 去重
            List<Integer> ids = clazzIds.stream().distinct().toList();
            // 根据员工id查询员工姓名
            List<Emp> emps = empService.listByIds(ids);
            // 双重for循环，为每个clazz对象的masterName赋值
            records.forEach(clazz -> {
                emps.stream().filter(emp -> emp.getId().equals(clazz.getMasterId()))
                        .findFirst()
                        .ifPresent(emp -> clazz.setMasterName(emp.getName()));
            });
        }

        // 为clazz表中的status赋值
        records.forEach(clazz -> {
            if(clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开班");
            } else if(clazz.getEndDate().isBefore(LocalDate.now())){
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("在读");
            }
        });


        return new PageResult<>(total, records);
    }
}
